#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdlib.h>

#include "fly.h"

#define MAX_LOOP (1000000)

int vol[MAX_LOOP] = {0};

void Print(void* args)
{
    struct timeval start, end;
    gettimeofday(&start, NULL);
    int size = 0;
    void* buff[MAX_LOOP] = {0};
    for (int i = 0; i < MAX_LOOP; ++i) {
        buff[i] = FlyMalloc(vol[i]);
    }
    for (int i = 0; i < MAX_LOOP; ++i) {
        FlyFree(&(buff[i]), size);
    }
    gettimeofday(&end, NULL);
    long elapse = (end.tv_sec - start.tv_sec) * 10e6 + \
        (end.tv_usec - start.tv_usec);
    printf("FlyMalloc time elapse: %f us\n", elapse / 10000000.0);
}

void MallocPrint(void* args)
{
    struct timeval start, end;
    gettimeofday(&start, NULL);
    int size = 0;
    void* buff[MAX_LOOP] = {0};
    for (int i = 0; i < MAX_LOOP; ++i) {
        buff[i] = malloc(vol[i]);
    }
    for (int i = 0; i < MAX_LOOP; ++i) {
        free(buff[i]);
    }
    gettimeofday(&end, NULL);
    long elapse = (end.tv_sec - start.tv_sec) * 10e6 + \
        (end.tv_usec - start.tv_usec);
    printf("malloc time elapse: %f us\n", elapse / 10000000.0);
}

int main(int argc, char* argv[])
{
    FlyInit(10240);

    for (int i = 0; i < MAX_LOOP; ++i) {
        vol[i] = rand() % (2 << 24);
    }
    pthread_t thread2;
    pthread_t thread1;
    pthread_t thread3;
    pthread_t thread4;
    pthread_t thread5;
    pthread_t thread6;
    pthread_create(&thread1, NULL, Print, NULL);
    pthread_create(&thread2, NULL, Print, NULL);
    pthread_create(&thread3, NULL, Print, NULL);
    pthread_create(&thread4, NULL, MallocPrint, NULL);
    pthread_create(&thread5, NULL, MallocPrint, NULL);
    pthread_create(&thread6, NULL, MallocPrint, NULL);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    pthread_join(thread3, NULL);
    pthread_join(thread4, NULL);
    pthread_join(thread5, NULL);
    pthread_join(thread6, NULL);
    FlyDestroy();
    return 0;
}